package com.financing.task.user;

import java.util.Date;

import com.financing.components.payment.Gateway;
import com.financing.model.Data;
import com.financing.model.user.BankCard;
import com.financing.model.user.User;
import com.financing.service.system.LoggerService;
import com.financing.service.user.BankCardService;
import com.financing.util.DateUtil;
import com.financing.util.Str;
import com.financing.util.XmlHelper;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 换绑卡查询定时任务
 * 
 * @author 无处不在的二叔
 */
public class ChangeBankCardTask implements Runnable {
	private static LoggerService log = new LoggerService();
	private static BankCardService bankCard = new BankCardService();

	@Override 
	@Before(Tx.class)
	public void run() {
		try {
			 for(BankCard card : bankCard.list(1, 999, Data.putStr("status","process")).getList()){
				 	User u = User.me.findById(card.getUserId());
				 	String code = DateUtil.getTimeStamp();
					XmlHelper res = Gateway.post("/queryChangeCard.action", 
						Data.put(
							"mchnt_txn_ssn",code,
							"login_id",u.getCode(),
							"txn_ssn",card.getCode(),
							"sign","login_id,mchnt_cd,mchnt_txn_ssn,txn_ssn"
						)
					);
					
					if(res.isSuccess()) {
						String status = res.getStr("examine_st");
						String summary = res.getStr("remark");
						if(Str.eq("1",status)) {		// 审核成功
							//将其他卡设为无效状态
							bankCard.setFailed(u.getId());
							// 更新新卡状态
							card.set("status", "success").update();
							// 更新用户信息
							u.setBankCard(card.getBankAccount()).setIsBindBankCard(1).setBindCardTime(new Date()).update();
							// 日志记录
							log.build("开户", "用户开户绑卡成功", u.getId(), "user");
						}else if(Str.eq("2",status)) {		// 审核失败
							// 更新新卡状态
							card.set("status", "failed").setSummary(summary).update();
							// 日志记录
							log.build("开户", "用户开户绑卡失败："+summary, u.getId(), "user");
						}
					}
			 }
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
